# pip install paho-mqtt

import paho.mqtt.client as mqtt  

  
# MQTT服务器地址和端口  

broker_address = "mqtt.example.com"  

port = 1883  

  

# 当连接成功时调用的回调函数  

def on_connect(client, userdata, flags, rc):  

    print(f"Connected with result code {rc}")  

    # 订阅主题  

    client.subscribe("your/topic")  

  

# 当接收到消息时调用的回调函数  

def on_message(client, userdata, msg):  

    print(f"Received message: {msg.payload.decode()} from topic: {msg.topic}")  

  

# 创建MQTT客户端实例  

client = mqtt.Client()  

  

# 设置连接成功时的回调函数  

client.on_connect = on_connect  

  

# 设置接收到消息时的回调函数  

client.on_message = on_message  

  

# 连接到MQTT服务器  

client.connect(broker_address, port, 60)  

  

# 开始客户端的网络循环  

client.loop_forever()